<script setup>
import { onMounted, ref } from 'vue';
import { convertFileSrc, invoke } from '@tauri-apps/api/core';
import { listen, emit } from '@tauri-apps/api/event';

// 解决系统图片资源加载问题
var path1 = "E:\\迅雷下载\\AI 图片生成.png"; //"/home/andy/asset/demo.png";
var logo = ref(convertFileSrc(path1));  // asset://localhost/xxxxxx.png
console.log("path1 to url:", path1, logo.value);

// JS call rust 并且有返回值object
async function call_js_1() {
    var resp = await invoke('js_call_rs', { user: 'tauri', password: 'poiwe3h4r5ip3yrhtew9ty' });
    console.log(resp);
    alert(JSON.stringify(resp));
}

// JS 接受 Rust/js event
var event_win_move = listen("tauri://move", (event) => {
    console.log("win move event:", event.payload); // { x: 200, y: 231 }
});

var event_js_custom = listen("my_event", (event) => {
    console.log("js custom event:", event.payload); //  { hello: "world" }
});

async function js_emit_event() {
    await emit("my_event", { hello: "world" });
}
onMounted(async () => {
    await list_music();
});

onUnmounted(async () => {
    event_win_move();
    event_js_custom();
});

var music_lists = ref([]);
var music_url = ref(null);

async function list_music() {
    var resp = await invoke('my_audio_scan', {
        path: "/home/andy/Music", //"/home/andy/asset"
        recursive: false,
    });
    music_lists.value = resp;
    console.log(resp[0]);
}

var audio_ref = ref(null);
function play_music(item) {
    var url = convertFileSrc(item.path);
    console.log(item.path, url);
    music_url.value = item.path;
    audio_ref.value.src = url;
    audio_ref.value.play();
}
</script>
<template>
    <n-scrollbar>
        <div class="flex flex-col gap-2">
            <h1 class="text-xl font-bold">PageTest for js and tauri</h1>
            <div class="flex flex-row gap-1">
                <n-button type="primary" @click="call_js_1">JS call rust</n-button>
                <n-button type="info" @click="js_emit_event">JS send event</n-button>
            </div>
            <div>
                <img :src="logo" width="200" height="200" />

            </div>
            <div class="flex flex-row gap-1">
                <n-button type="primary" @click="list_music">List music</n-button>
            </div>
            <audio src="" controls ref="audio_ref"></audio>
            <div class=" bg-red-400">{{ music_url }}</div>
            <ul>
                <li v-for="item in music_lists" :key="item.title" class="hover:bg-gray-200 text-sm" @click="play_music(item)">
                    {{ item.path }} - {{ item.title }} - {{ item.artist }} - {{ item.album }} - {{ item.duration }}s - {{ item.bitrate }}K - {{ item.sample_rate }}Hz - {{ item.bit_depth }}B
                </li>
            </ul>
            
        </div>
    </n-scrollbar>

</template>

<style lang="scss" scoped></style>